package com.ilxqx.framework.amqp.service.impl;

import com.ilxqx.framework.amqp.entity.SysMessageLog;
import com.ilxqx.framework.amqp.enumeration.SysMessageLogStatusEnum;
import com.ilxqx.framework.amqp.form.search.SysMessageLogSearchForm;
import com.ilxqx.framework.amqp.repository.SysMessageLogRepository;
import com.ilxqx.framework.amqp.service.SysMessageLogService;
import com.ilxqx.framework.system.service.impl.AbstractSearchableServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 系统任务服务实现类
 * @author venus
 */
@Service
public class SysMessageLogServiceImpl extends AbstractSearchableServiceImpl<SysMessageLog, Long, SysMessageLogSearchForm> implements SysMessageLogService {

    private final SysMessageLogRepository repository;

    @Autowired
    public SysMessageLogServiceImpl(SysMessageLogRepository repository) {
        super(repository);
        this.repository = repository;
    }

    /**
     * 根据消息ID改变消息状态
     *
     * @param messageId 消息ID
     * @param status    消息状态
     */
    @Override
    public void changeMessageStatus(Long messageId, SysMessageLogStatusEnum status) {
        Optional<SysMessageLog> sysMessageLogOptional = this.get(messageId);
        if (sysMessageLogOptional.isPresent()) {
            // 消息存在，进行处理
            SysMessageLog sysMessageLog = sysMessageLogOptional.get();

            boolean sending = sysMessageLog.getStatus().equals(SysMessageLogStatusEnum.SENDING);
            boolean sendingSuccess = sysMessageLog.getStatus().equals(SysMessageLogStatusEnum.SENDING_SUCCESS)
                    && SysMessageLogStatusEnum.HANDLING_FAILURE.equals(status);
            boolean sendingFailure = sysMessageLog.getStatus().equals(SysMessageLogStatusEnum.SENDING_FAILURE)
                    && (SysMessageLogStatusEnum.SENDING_SUCCESS.equals(status)
                    || SysMessageLogStatusEnum.HANDLING_FAILURE.equals(status));

            if (sending || sendingSuccess || sendingFailure) {
                sysMessageLog.setStatus(status);
                this.modify(sysMessageLog);
            }
        }
    }

    /**
     * 创建空的或者带有默认值的实体对象
     *
     * @return 实体对象
     */
    @Override
    public SysMessageLog create() {
        SysMessageLog sysMessageLog = new SysMessageLog();
        sysMessageLog.setTryCount(0);
        sysMessageLog.setNextRetryTime(LocalDateTime.now().plusMinutes(2));
        return sysMessageLog;
    }

    /**
     * 获取需要重试的消息
     *
     * @param maxRetryCount   最大重试次数
     * @param needRetryStatuses 需要重试的消息状态
     * @return 消息List
     */
    @Override
    public List<SysMessageLog> getRetryList(Integer maxRetryCount, List<String> needRetryStatuses) {
        return repository.getRetryList(maxRetryCount, needRetryStatuses);
    }

}
